package cn.tedu.review;/**
 * @Author 金帮嘉诚 @Date 2021-06-24 星期四 10:12
 */
/*本类用于测试*/

import sun.awt.windows.ThemeReader;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 知识点
 */
public class TestReentrantReadWriteLock {
    public static void main(String[] args) {
        SaleTicketsV3 s1=new SaleTicketsV3();
        Thread t1=new Thread(s1);
        Thread t2=new Thread(s1);
        Thread t3=new Thread(s1);
        Thread t4=new Thread(s1);

        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}

class SaleTicketsV3 implements Runnable {
    int ticketNumber = 100;
    ReentrantReadWriteLock writeLock = new ReentrantReadWriteLock();

    @Override
    public void run() {
        while (true) {
            writeLock.writeLock().lock();

            try {
                if (ticketNumber > 0) {

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "=" + ticketNumber--);
                }
                if (ticketNumber <= 0) break;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                writeLock.writeLock().unlock();
            }
        }

    }
}
